/**
 * 
 */
package org.t2.game.server.module.data.service;

import java.util.ArrayList;
import java.util.List;

import org.gaming.service.repository.IRepository;
import org.gaming.service.repository.Repository;
import org.gaming.service.service.jvm.OneToManyService;
import org.springframework.stereotype.Service;
import org.t2.game.server.module.data.model.Data;
import org.t2.game.server.module.data.model.DataLog;

/**
 * @author YY
 */
@Service
public class DataService extends OneToManyService<Data> {
	
	public List<Data> getModuelDatas(long playerId, String dataType) {
		return this.repository().listByKeys(playerId, dataType);
	}
	
	@Override
	public void mergeServer(int mergeDbZoneId) {
		IRepository<Data> repository = Repository.get(mergeDbZoneId, Data.class);
		List<Data> mergeDatas = repository.getBaseDao().queryAll();
		this.repository().insertAll(mergeDatas);
	}
	
	public void insert(List<Data> datas, String reason) {
		this.insert(datas);
		loggerDatas(datas, "insert", reason);
	}
	
	public void update(List<Data> datas, List<Data> needLogDatas, String reason) {
		this.update(datas);
		loggerDatas(needLogDatas, "update", reason);
	}

	public void delete(List<Data> datas, String reason) {
		this.repository().deleteAll(datas);
		loggerDatas(datas, "delete", reason);
	}
	
	private void loggerDatas(List<Data> datas, String operation, String reason) {
		List<DataLog> dataLogs = new ArrayList<>();
		for(Data data : datas) {
			DataLog dataLog = new DataLog();
			dataLog.setPlayerId(data.getPlayerId());
			dataLog.setOperation(operation);
			dataLog.setReason(reason);
			dataLog.setDataType(data.getDataType());
			dataLog.setDataId(data.getDataId());
			dataLog.setPlaintext(data.getPlaintext());
			dataLogs.add(dataLog);
		}
		this.log().insertAll(dataLogs);
	}
	
	
	private IRepository<DataLog> log;
	private IRepository<DataLog> log() {
		if(log == null) {
			log = Repository.get(DataLog.class);
		}
		return log;
	}
}
